<template>
  <div class="detail-box">
    <load :show="show" :overlay="overlay" />
    <div class="detail-bg" :style="'background-image:url('+ bookDetail.image +')'"></div>
    <div class="detail-wrap"></div>
    <div class="detail-tabbar" :style="tabbarStyle">
      <van-icon :color="tabbarIconStyle" name="arrow-left" @click="handleToBack" />
      <span v-show="tabbarStyle !=''">{{bookDetail.name}}</span>
      <van-icon
        :color="tabbarIconStyle"
        name="http://foglake.sanye666.top/images/icon/share.png"
        @click="handleToShare"
      />
    </div>
    <div class="detail-content">
      <div class="detail-top">
        <div class="detail-letf">
          <div class="detai-main">
            <span class="detail-name">{{bookDetail.name}}</span>
            <div class="detail-info">
              <span class="detail-writer">{{bookDetail.writer}}</span>
              <span class="detail-over">{{bookDetail.is_over}} | {{bookDetail.type}}</span>
            </div>
          </div>
          <div class="detail-new" @click="handleToNew">
            <span>{{bookDetail.new_chapter}}</span>
            <van-icon name="arrow" />
          </div>
        </div>
        <van-image :src="bookDetail.image" class="detail-img" fit="cover">
          <template v-slot:loading>
            <van-loading type="spinner" size="20" />
          </template>
        </van-image>
      </div>
      <div class="detail-intro">
        <div>简介：</div>
        <div class="van-multi-ellipsis--l3">{{bookDetail.intro}}</div>
      </div>
    </div>
    <div class="detail-list">
      <div class="list-nav">
        <van-icon name="arrow-up" size="14" @click="handleToTop" />
        <span>目录</span>
        <span @click="handleToReverse">{{reverseFlag ? '正序':'倒序'}}</span>
      </div>
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="loadChapter"
        class="chapter-list"
      >
        <van-cell
          v-for="(item, index) in chapterList"
          :key="index"
          :title="item.title"
          @click="handleToRead(item.book_id,item.id)"
        />
      </van-list>
    </div>
    <div class="detail-bottom">
      <span class="add-shelf" @click="handleAddBookShelf">{{flag?'撤出书架':'加入书架'}}</span>
      <span
        class="read-start"
        @click="handleToRead(bookDetail.id, bookDetail.first_chapter_id)"
      >开始阅读</span>
    </div>
    <van-share-sheet v-model="showShare" title="立即分享给好友" :options="options" @select="onSelect" />
  </div>
</template>

<script>
import Taro, { getCurrentInstance } from "@tarojs/taro";
import { getChapterDetail, getChapterList } from "@api/chapter";
import bookshelfVue from "../bookshelf/bookshelf.vue";
import Load from "@components/Load";
export default {
  name: "bookdeatail",
  components: { Load },
  data() {
    return {
      showShare: false,
      options: [
        [
          { name: "微信", icon: "wechat" },
          { name: "微博", icon: "weibo" },
          { name: "QQ", icon: "qq" },
        ],
        [
          { name: "复制链接", icon: "link" },
          { name: "分享海报", icon: "poster" },
          { name: "二维码", icon: "qrcode" },
        ],
      ],
      bookDetail: {},
      loading: false,
      finished: false,
      chapterCount: 0,
      chapterList: [],
      chapterListShow: false,
      introMore: false,
      flag: false,
      reverseFlag: false,
      overlay: true,
      show: false,
      tabbarStyle: "",
      tabbarIconStyle: "rgba(255,255,255,0.5)",
      currentPage:1,
      lastPage:10,
      pageSize:50
    };
  },
  created() {
    this.init();
  },
  mounted() {
    window.addEventListener("scroll", this.handleScroll);
  },
  methods: {
    async init() {
      this.show = true;
      let { id } = getCurrentInstance().router.params;
      this.bookId = id;
      await this.getChapterDetail(id);
      await this.handleGetBookShelf(id);
      this.show = false;
    },
    handleToShare() {
      this.showShare = true;
    },
    onSelect(option) {
      let oInput = document.createElement("input");
      oInput.value = window.location.href;
      document.body.appendChild(oInput);
      oInput.select();
      document.execCommand("Copy");
      oInput.className = "oInput";
      oInput.style.display = "none";
      let param = {};
      let targetUrl = "";
      switch (option.name) {
        case "微信":
          Taro.showModal({
            title: "分享到微信好友",
            content: "复制链接成功,打开微信分享吧!",
            success: function (res) {
              window.location.href = "weixin://";
            },
          });
          break;
        case "QQ":
          param = {
            url: window.location.href,
            desc: `我正在三叶中文网上阅读${this.bookDetail.name},一起来看吧!`,
            title: `我正在三叶中文网上阅读${this.bookDetail.name},一起来看吧!`,
            site: "三叶中文网",
          };
          let s = [];
          for (let i in param) {
            s.push(i + "=" + encodeURIComponent(param[i] || ""));
          }
          targetUrl =
            "http://connect.qq.com/widget/shareqq/iframe_index.html?" +
            s.join("&");
          window.open(targetUrl, "qq", "height=520, width=720");
          break;
        case "微博":
          param = {
            url: window.location.href,
            type: "3",
            count: "1",
            title: `我正在三叶中文网上阅读${this.bookDetail.name},一起来看吧!`,
            rnd: new Date().valueOf(),
          };
          let temp = [];
          for (let p in param) {
            temp.push(p + "=" + encodeURIComponent(param[p] || ""));
          }
          targetUrl =
            "http://service.weibo.com/share/share.php?" + temp.join("&");
          window.open(targetUrl, "sinaweibo", "height=430, width=400");
          break;
        case "复制链接":
          Taro.showToast({ title: "复制链接成功!", icon: "none" });
          break;
        case "二维码":
          let url = window.location.href,
            encodePath = encodeURIComponent(url),
            targetUrl = "http://qr.liantu.com/api.php?text=" + encodePath;
          window.open(targetUrl, "weixin", "height=320, width=320");
          break;
      }
      this.showShare = false;
    },
    handleToBack() {
      Taro.navigateBack();
    },
    getChapterDetail(id) {
      return new Promise((resolve, reject) => {
        getChapterDetail({ id }).then((res) => {
          this.bookDetail = res.data;
          resolve("ok");
        });
      });
    },
    getChapterList(id) {
      	this.loading = true
				if(this.currentPage - 1 == this.lastPage){
          this.loading = false
          this.finished = true
					return
				}
      return new Promise((resolve, reject) => {
        getChapterList({ id,page:this.currentPage,pageSize:this.pageSize }).then((res) => {
          this.chapterList = this.chapterList.concat(res.data.data)
          if (res.data.chapterCount == 0) {
            Taro.showModal({
              content: "未找到章节列表!",
              showCancel: false,
              success: function (res) {
                if (res.confirm) {
                  Taro.navigateBack();
                }
              },
            });
          } else {
           		this.currentPage = this.currentPage + 1;
							this.chapterCount = res.data.total;
              this.lastPage = res.data.last_page;
              this.loading = false;
          }
          resolve("ok");
        });
      });
    },
    handleToChapterList() {
      this.chapterListShow = true;
    },
    handleIntroMore() {
      this.introMore = !this.introMore;
    },
    handleToRead(id, chapter_id) {
      Taro.navigateTo({
        url: `/pages/read/read?id=${id}&chapter_id=${chapter_id}`,
      });
    },
    // 查询书架缓存
    handleGetBookShelf(id) {
      try {
        let bookShelf = Taro.getStorageSync("bookShelf");
        if (bookShelf) {
          let _bookShelf = JSON.parse(bookShelf);
          if (_bookShelf[id]) {
            this.flag = true;
          }
        }
      } catch (e) {
        console.log(e);
      }
    },
    // 加入/撤出书架
    handleAddBookShelf() {
      if (this.flag) {
        let bookShelf = Taro.getStorageSync("bookShelf");
        if (bookShelf) {
          let _bookShelf = JSON.parse(bookShelf);
          if (_bookShelf[this.bookDetail.id]) {
            delete _bookShelf[this.bookDetail.id];
            Taro.setStorageSync("bookShelf", JSON.stringify(_bookShelf));
            this.flag = false;
            Taro.showToast({ title: "成功撤出书架", icon: "none" });
          }
        }
      } else {
        let bookShelf = Taro.getStorageSync("bookShelf");
        let _bookShelf = bookShelf ? JSON.parse(bookShelf) : {};
        _bookShelf[this.bookDetail.id] = {
          id: this.bookDetail.id,
          index: "1",
          chapterCount: this.chapterCount,
          chapter_id: this.bookDetail.first_chapter_id,
          name: this.bookDetail.name,
          type: this.bookDetail.type,
          writer: this.bookDetail.writer,
          is_over: this.bookDetail.is_over,
          image: this.bookDetail.image,
        };
        Taro.setStorageSync("bookShelf", JSON.stringify(_bookShelf));
        this.flag = true;
        Taro.showToast({ title: "成功加入书架", icon: "none" });
      }
    },
    loadChapter() {
      this.getChapterList(this.bookId);
    },
    handleToReverse() {
      this.chapterList = this.chapterList.reverse();
      this.reverseFlag = !this.reverseFlag;
    },
    handleToTop() {
      window.scrollTo({
        top: 0,
        behavior: "smooth",
      });
    },
    handleToNew() {
      if (this.bookDetail.last_chapter_id) {
        Taro.navigateTo({
          url: `/pages/read/read?id=${this.bookDetail.id}&chapter_id=${this.bookDetail.last_chapter_id}`,
        });
      }
    },
    handleScroll() {
      let scrollTop =
        window.pageYOffset ||
        document.documentElement.scrollTop ||
        document.body.scrollTop;
      if (scrollTop === 0) {
        this.tabbarStyle = "";
        this.tabbarIconStyle = "rgba(255,255,255,0.5)";
      } else {
        this.tabbarIconStyle = "rgba(0,0,0,1)";
        if (scrollTop < 50) {
          this.tabbarStyle = `background:rgba(255,255,255,${scrollTop / 50})`;
        } else {
          this.tabbarStyle = "background:rgba(255,255,255,1)";
        }
      }
    },
  },
};
</script>

<style scoped>
.detail-box {
  padding: 40px 40px;
}
.detail-bg {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background-repeat: no-repeat;
  background-size: 100vw 100vh;
  filter: blur(40px);
}
.detail-wrap {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background: linear-gradient(
    0deg,
    rgba(245, 248, 252, 1) 0%,
    rgba(6, 27, 65, 1) 100%
  );
  opacity: 0.7;
}
.detail-tabbar {
  position: fixed;
  left: 0;
  top: 0;
  padding: 20px 40px;
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  z-index: 10;
}

.detail-tabbar span {
  font-size: 28px;
}

.detail-bottom {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 100px;
  display: flex;
  justify-content: space-between;
  padding: 16px 34px;
  font-size: 22px;
  align-items: center;
  background: rgba(255, 255, 255, 1);
  box-shadow: 0px 0px 23px 0px rgba(6, 27, 65, 0.16);
  border-radius: 40px 40px 0px 0px;
}
.add-shelf {
  width: 50%;
  text-align: center;
}
.read-start {
  width: 95%;
  height: 68px;
  background: rgba(145, 199, 255, 1);
  border-radius: 50px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
}
.detail-content {
  position: relative;
  display: flex;
  flex-direction: column;
  padding: 40px 18px;
}
.detail-top {
  display: flex;
  justify-content: space-between;
}
.detail-left {
}
.detail-main {
}
.detail-name {
  font-size: 36px;
  font-family: Alibaba PuHuiTi;
  font-weight: bold;
  color: rgba(255, 255, 255, 1);
  opacity: 0.85;
}
.detail-writer {
  font-size: 20px;
  font-family: Alibaba PuHuiTi;
  font-weight: bold;
  color: rgba(255, 255, 255, 1);
  opacity: 0.85;
}
.detail-type,
.detail-over {
  font-size: 18px;
  font-family: Alibaba PuHuiTi;
  font-weight: bold;
  color: rgba(255, 255, 255, 1);
  line-height: 28px;
  opacity: 0.65;
}
.detail-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.detail-new {
  width: 440px;
  font-size: 20px;
  font-family: Alibaba PuHuiTi;
  font-weight: bold;
  color: rgba(255, 255, 255, 1);
  line-height: 28px;
  opacity: 0.85;
  padding: 26px 0;
  border-top: 1px solid rgba(255, 255, 255, 0.25);
  border-bottom: 1px solid rgba(255, 255, 255, 0.25);
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.detail-img {
  width: 144px;
  height: 194px;
  border-radius: 16px;
}
.detail-info {
}
.detail-intro {
  font-size: 22px;
  font-family: Alibaba PuHuiTi;
  font-weight: 400;
  color: rgba(255, 255, 255, 1);
  line-height: 36px;
  opacity: 0.65;
}
.list-nav {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 42px 40px;
  position: relative;
  background: rgba(255, 255, 255, 1);
  border-radius: 24px 24px 0 0;
}
.list-nav span {
  font-size: 32px;
  font-family: Alibaba PuHuiTi;
  font-weight: bold;
  color: rgba(6, 27, 65, 1);
  opacity: 0.75;
}
.list-nav span:last-child {
  font-size: 22px;
  font-family: Alibaba PuHuiTi;
  font-weight: 400;
  text-decoration: underline;
  color: rgba(146, 200, 255, 1);
}
.van-list span {
  font-size: 22px;
  font-family: Alibaba PuHuiTi;
  font-weight: 400;
  color: rgba(6, 27, 65, 1);
  opacity: 0.75;
}
.chapter-list {
  border-radius: 0 0 26px 26px;
  margin-bottom: 100px;
  height: 70vh;
  overflow: scroll;
}
.van-icon__image {
  opacity: 0.5;
}
</style>